package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.SelectionAdapter;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.CartoonVo;
import com.jdy.haoduoai.model.CategoryItem;
import com.jdy.haoduoai.model.HotSearchKey;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.pulltorefresh.PullableGridView;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

//import com.jdy.haoduoai.R;

public class ChoiceActivity extends BaseActivity implements OnRefreshListener,
        OnItemClickListener {

    @InjectView(id = R.id.refresh_view)
    private PullToRefreshLayout pullToRefreshLayout;
    @InjectView(id = R.id.content_views)
    private PullableGridView gridView;

    @InjectView(id = R.id.emptylayout)
    private LinearLayout emptylayout;
    @InjectView(id = R.id.reloadRippleView)
    private RippleView reloadRippleView;

    private SelectionAdapter storyListAdapter;

    private CategoryItem categoryItem = null;
    private HotSearchKey searchKey = null;
    private int mLastpage = 1;
    private ArrayList<CartoonVo> mAdapterList = null;
    private ArrayList<CartoonVo> mArrayList = null;
    public boolean isrefreshlist = false;
    private LeUser leUser;
    private String title;
    private String key;
    private ACache mCache;
    private JSONArray jsonArr;

    @Override
    @SuppressLint("InflateParams")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choice);
        initialize();
        initlistener();
        requestData(true, true);
    }

    private String searchType;

    private void initialize() {
        mCache = ACache.get(this);

        Intent intent = getIntent();
        if (intent.getSerializableExtra("categoryitem") != null) {
            categoryItem = (CategoryItem) intent.getSerializableExtra("categoryitem");
            title = categoryItem.name;
        } else if (intent.getSerializableExtra("searchkey") != null) {
            searchKey = (HotSearchKey) intent.getSerializableExtra("searchkey");
            title = searchKey.name;
            key = title;
        } else {
            key = getIntent().getStringExtra("key");
            title = key;
        }

        searchType = getIntent().getStringExtra("searchType");

        setTitle(title);
        mAdapterList = new ArrayList<>();
        mArrayList = new ArrayList<>();
        leUser = LeXiaoXiaoBanApp.getInstance().getUser();
    }

    private void initlistener() {
        gridView.setOnItemClickListener(this);
        reloadRippleView
                .setOnRippleCompleteListener(new OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        mLastpage = 1;
                        isrefreshlist = true;
                        requestData(true, false);
                    }
                });
        pullToRefreshLayout.setOnRefreshListener(this);
    }

    private void requestData(boolean isShowLoading, boolean isFromCache) {
        if (isShowLoading) {
            showloading("加载中..");
        }

        if (Tools.isEmpty(searchType) && isFromCache) {
            jsonArr = mCache.getAsJSONArray(title);
        }

        if (jsonArr != null && jsonArr.length() > 0 && isFromCache) {
            dismissLoading();
            try {
                if (mAdapterList != null) {
                    mAdapterList.clear();
                }
                if (isrefreshlist) {
                    mArrayList.clear();
                }
                for (int i = 0; i < jsonArr.length(); i++) {
                    JSONObject obj = ((JSONObject) jsonArr.opt(i));

                    if (Tools.isNotEmpty(obj.toString())) {
                        CartoonVo itemVo = JsonSerializer.getInstance().deserialize(
                                obj.toString(), CartoonVo.class);
                        mAdapterList.add(itemVo);
                    }

                }
            } catch (Exception e) {
            }
            mArrayList.addAll(mAdapterList);
            setView();
        } else {

        if (Tools.isNotEmpty(searchType)) {
            new CustomAsyncTask(ChoiceActivity.this, new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity, ResponseResult result) {
                    dismissLoading();
                    if (result.isSuccess()) {
                        try {
                            JSONObject json = new JSONObject(result.data);
                            String data = json.optString("data");
                            final JSONArray array = new JSONArray(data);

                            if (mAdapterList != null) {
                                mAdapterList.clear();
                            }
                            if (isrefreshlist) {
                                mArrayList.clear();
                            }
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = ((JSONObject) array.opt(i));
                                if (Tools.isNotEmpty(obj.toString())) {
                                    CartoonVo itemVo = JsonSerializer.getInstance()
                                            .deserialize(obj.toString(), CartoonVo.class);
                                    if (Tools.isNotEmpty(itemVo.catalog)
                                            && !itemVo.catalog.contains("book")) {
                                        mAdapterList.add(itemVo);
                                    }

                                }

                            }
                        } catch (Exception e) {
                        }
                        mArrayList.addAll(mAdapterList);
                        setView();
                    } else {
                        toastShow(result.data.toString());
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                    if (leUser == null) {
                        leUser = Tools.restoreLeUser();
                    }

                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                    if (Tools.isNotEmpty(searchKey)) {
                        param_.put("name", searchKey.name);
                    } else {
                        param_.put("name", key);
                    }

                    param_.put("page", mLastpage);
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    if (searchType.contains("album")) {
                        return HttpUtils.startRequest(HttpUtils.HOST_API
                                        + HttpUtils.GET_CATALOG_ALBUM, param_,
                                HttpUtils.TAG_GET_REQUEST);
                    } else {

                        return HttpUtils
                                .startRequest(HttpUtils.HOST_API + HttpUtils.GET_STORY_LIST,
                                        param_, HttpUtils.TAG_GET_REQUEST);

                    }
                }
            }).execute();

        } else {

            new CustomAsyncTask(ChoiceActivity.this, new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity, ResponseResult result) {
                    dismissLoading();
                    if (result.isSuccess()) {

                        try {
                            JSONObject json = new JSONObject(result.data);
                            String data = json.optString("data");
                            final JSONArray array = new JSONArray(data);

                            new Thread() {
                                @Override
                                public void run() {
                                    if (jsonArr != null) {
                                        mCache.remove(title);
                                    }
                                    mCache.put(title, array);
                                }

                                ;
                            }.start();

                            if (mAdapterList != null)
                                mAdapterList.clear();
                            if (isrefreshlist) {
                                mArrayList.clear();
                            }
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = ((JSONObject) array.opt(i));

                                if (Tools.isNotEmpty(obj.toString())) {
                                    CartoonVo itemVo = JsonSerializer.getInstance()
                                            .deserialize(obj.toString(), CartoonVo.class);
                                    mAdapterList.add(itemVo);
                                }

                            }
                        } catch (Exception e) {
                        }
                        mArrayList.addAll(mAdapterList);
                        setView();
                    } else {
                        toastShow(result.data.toString());
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                    if (leUser == null) {
                        leUser = Tools.restoreLeUser();
                    }

                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                    if (categoryItem != null) {
                        param_.put("category_id", categoryItem.id);
                    } else if (searchKey != null) {
                        param_.put("name", key);
                    } else {
                        param_.put("name", key);
                    }

                    param_.put("page", mLastpage);
                    if (null != categoryItem && categoryItem.id == 39) {
                        //如果是39,证明是金牌新概念,多加一个参数
                        param_.put("ts_id", "9");
                    }

                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    if (null != categoryItem && categoryItem.id == 39) {
                        return HttpUtils
                                .startRequest(HttpUtils.HOST_API + "/api/2.0/catalog/teacher/album/stu_get_ta",
                                        param_, HttpUtils.TAG_GET_REQUEST);

                    } else {
                        return HttpUtils.startRequest(HttpUtils.HOST_API
                                        + HttpUtils.GET_CATALOG_ALBUM, param_,
                                HttpUtils.TAG_GET_REQUEST);

                    }

                }
            }).execute();
        }
        }
    }

    private void setView() {
        if (storyListAdapter == null) {
            storyListAdapter = new SelectionAdapter(ChoiceActivity.this, mArrayList);
            gridView.setAdapter(storyListAdapter);
        } else {
            storyListAdapter.notifyDataSetChanged();
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        }
        if (storyListAdapter.getCount() == 0) {
            emptylayout.setVisibility(View.VISIBLE);
        } else {
            emptylayout.setVisibility(View.GONE);
        }
    }

    private CarlaClassicVo convert2CarlaClassicVo(CartoonVo recommendStroy) {

        if (recommendStroy == null)
            return null;
        CartoonVo lhr = recommendStroy;
        CarlaClassicVo ccv = new CarlaClassicVo();
        ccv.id = lhr.id; // );
        ccv.category_id = lhr.category_id; // );
        ccv.catalog = lhr.catalog; // );
        ccv.name = lhr.name; // );
        ccv.cover = lhr.cover;// );
        ccv.url = lhr.url;// );
        ccv.enabled = lhr.enabled; // );
        ccv.sort = lhr.sort; // );
        ccv.length = lhr.length; // );
        ccv.agefrom = 0; // );
        ccv.ageto = 0;
        ccv.lines = lhr.lines; // );
        ccv.created_at = lhr.created_at; // );
        ccv.updated_at = lhr.updated_at; // );
        ccv.deleted_at = lhr.deleted_at; // );
        ccv.followers = lhr.followers;// );
        ccv.corner_icon = lhr.corner_icon; // );
        ccv.author = lhr.author; // );
        ccv.tags = lhr.tags; // );

        return ccv;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        CartoonVo vo = mArrayList.get(position);
        Intent intent = new Intent();
        if (title.equals("宝宝电台")) {
            intent.setClass(this, RadioDetailActivity.class);
        } else {
            intent.setClass(this, StoryDetailActivity.class);
        }

        if (Tools.isNotEmpty(searchType)) {
            if (searchType.contains("story")) {
                if (vo.catalog.contains("dub")) {
//                    if (vo.category_id.contains("36")) { // 绘本
//                        // intent.setClass(this, StoryBookActivity.class);
//                        // Bundle bundle = new Bundle();
//                        // bundle.putSerializable("illustratedstory", vo);
//                        // intent.putExtras(bundle);
//                        // startActivity(intent);
//                    } else { // 故事
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("carlaclassic", convert2CarlaClassicVo(vo));
                    intent.putExtras(bundle);
                    intent.setClass(this, RecordActivity2.class);
                    startActivity(intent);
//                    }

                    return;
                }
            } else {
                intent.setClass(this, StoryDetailActivity.class);
            }
        }

        Bundle bundle = new Bundle();
        bundle.putSerializable("categoryItemjp", vo);
        intent.putExtras(bundle);
        intent.putExtra("JPid",categoryItem.id);

        intent.putExtra("id", vo.id);
        startActivity(intent);
    }

    @SuppressWarnings("unused")
    private void playvideo(final int sid, final String status) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    toastShow("已推送到设备播放");
                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        toastShow(result.data);
                    }
                }

            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();

                int uid = -1, volume = -1, minutes = -1;
                param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_ACTION_I, "play");
                param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
                param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
                //  param_.put("mode", "im");

                if (sid != -1) {
                    param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
                }

                param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mLastpage = 1;
        isrefreshlist = true;

        if (mCache != null) {
            mCache.remove(title);
        }

        requestData(false, false);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        mLastpage++;
        isrefreshlist = false;
        requestData(false, false);
    }
}
